﻿namespace Deppton.Repositories.Filesystem
{
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Xml.Linq;

    /// <summary>
    /// Filesystem based implementation for handling suvey assignations.
    /// </summary>
    public class FilesystemSurveysAssignationsHandler : ISurveysAssignationsHandler
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="FilesystemSurveysAssignationsHandler"/> class.
        /// </summary>
        /// <param name="storagePath">The storage path.</param>
        public FilesystemSurveysAssignationsHandler(string storagePath)
        {
            this.StoragePath = storagePath;
        }

        /// <summary>
        /// Gets or sets the storage path.
        /// </summary>
        /// <value>The storage path.</value>
        public string StoragePath
        {
            get;
            set;
        }

        /// <summary>
        /// Finds the assigned surveys for a given user.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <returns>Assignad surveys for the given user.</returns>
        public ICollection<string> FindAssignedSurveysForUser(string userName)
        {
            var assignations = XDocument.Load(Path.Combine(this.StoragePath, "assignations.xml"));

            return assignations.Root
                .Element("users")
                .Elements("user")
                .SingleOrDefault(e => (string)e.Attribute("id") == userName)
                .Elements("survey")
                .Select(e => (string)e.Attribute("id"))
                .ToList();
        }
    }
}
